(function() {

    // Localize jQuery variable
    var jQuery;

    /******** Load jQuery if not present *********/
    if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type","text/javascript");
        script_tag.setAttribute("src",
            "https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
        if (script_tag.readyState) {
            script_tag.onreadystatechange = function () { // For old versions of IE
                if (this.readyState == 'complete' || this.readyState == 'loaded') {
                    scriptLoadHandler();
                }
            };
        } else { // Other browsers
            script_tag.onload = scriptLoadHandler;
        }
        // Try to find the head, otherwise default to the documentElement
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    } else {
        // The jQuery version on the window is the one we want to use
        jQuery = window.jQuery;
        main();
    }

    /******** Called once jQuery has loaded ******/
    function scriptLoadHandler() {
        // Restore $ and window.jQuery to their previous values and store the
        // new jQuery in our local jQuery variable
        jQuery = window.jQuery.noConflict(true);
        // Call our main function
        main();
    }

    /******** Our main function ********/
    function main() {
        jQuery(document).ready(function($) {
            // We can use jQuery 1.4.2 here
            var location_id = "weatherwidget3";
            var widgetFormat = 'w';
            var locateMeOn = true;

            var css_link = $("<link>", {
                rel: "stylesheet",
                type: "text/css",
                href: 'https://widget.meteomatics.com/static/css/widgetstylesheet.css'
            });
            css_link.appendTo('head');

            var aTag = '<p id="geolocationerror" style="display:none;"></p><a class="company-widget" href="https://www.meteomatics.com/"  target="_blank">';
            var divLocation = '<div class="location-widget"></div>';
            var buttonLocation = '';
            if(locateMeOn){
                buttonLocation = '<button class="myLocationButton" >locate me</button>';
            }

            var startDivWeather = '<div class="weather-widget">'
            var startDivDay = '<div class="day">'
            var divWeekday = '<div class="weekday"></div>'
            var divSym = '<div class="sym"></div>'
            var divTemp1 = '<div class="text temp1"></div>'
            var divTemp2 = '<div class="text temp2"></div>'
            var closeDiv = '</div>';
            var closeATag = '</a>';
            var unitBtn = '<button class="switchUnitButton">u</button>'

            if(widgetFormat == 'w'){
                $('#'+ location_id).html(
                    divLocation
                    + buttonLocation
                    + aTag
                    + startDivWeather
                    + startDivDay
                    + divWeekday
                    + divSym
                    + divTemp2
                    + divTemp1
                    + closeDiv
                    + startDivDay
                    + divWeekday
                    + divSym
                    + divTemp2
                    + divTemp1
                    + closeDiv
                    + startDivDay
                    + divWeekday
                    + divSym
                    + divTemp2
                    + divTemp1
                    + closeDiv
                    + closeDiv
                    + closeATag
                    + unitBtn
                );
            }else{
                $('#'+ location_id).html(
                    divLocation
                    + aTag
                    + startDivWeather
                    + startDivDay
                    + divSym
                    + divWeekday
                    + divTemp1
                    + divTemp2
                    + closeDiv
                    + startDivDay
                    + divSym
                    + divWeekday
                    + divTemp1
                    + divTemp2
                    + closeDiv
                    + startDivDay
                    + divSym
                    + divWeekday
                    + divTemp1
                    + divTemp2
                    + closeDiv
                    + closeDiv
                    + closeATag
                    + buttonLocation
                    + unitBtn
                );
            }

            var weekday = new Array(7);
            weekday[0] = "Sunday";
            weekday[1] = "Monday";
            weekday[2] = "Tuesday";
            weekday[3] = "Wednesday";
            weekday[4] = "Thursday";
            weekday[5] = "Friday";
            weekday[6] = "Saturday";

            var convertTemperature = function(currentUnit, targetUnit, value) {
                let result;

                // Convert from current unit to Kelvin
                switch (currentUnit) {
                    case "f":
                        result = (value - 32) * 5 / 9 + 273.15;
                        break;
                    case "c":
                        result = value + 273.15;
                        break;
                    case "k":
                        result = value;
                        break;
                    default:
                        return "Invalid input for current unit.";
                }

                // Convert from Kelvin to target unit
                switch (targetUnit) {
                    case "f":
                        result = (result - 273.15) * 9 / 5 + 32;
                        break;
                    case "c":
                        result = result - 273.15;
                        break;
                    case "k":
                        result = result;
                        break;
                    default:
                        return "Invalid input for target unit.";
                }

                return Math.round(result);
            }


            /* Example
            var locationName = 'St. Gallen';
            var weatherSymbolArray = [5, 7, 1];
            var dateArray = [new Date("2017-01-24T00:00:00Z") ,new Date("2017-01-25T00:00:00Z") ,new Date("2017-01-26T00:00:00Z")]; //new Date();var n = d.getDay(); getTime(); ms
            var tempMaxArray = [2, 12, 15];
            var tempMinArray = [-3, 3, 9];*/

            var locationName = "Puerto Rosales Port";
            var weatherSymbolArray = [8, 8, 1];
            var dateArray = [new Date("2025-02-22T21:00:00Z"), new Date("2025-02-23T21:00:00Z"), new Date("2025-02-24T21:00:00Z"), ];
            var tempMaxArray = [31.1, 28.2, 26.9];
            var tempMinArray = [23.3, 24.4, 23.3];
            var latlon = '-38.933333_-62.066667';
            var unit = 'c';
            var units = {'c': '&nbsp;&#8451;', 'f': '&nbsp;&#8457;'};

            // tempMaxArray and tempMinArray stays always on the initialUnit values
            const initialUnit = unit;

            $('#' + location_id + ' .switchUnitButton').css({
                position: 'absolute',
                right: 0,
                bottom: 0,
                fontSize: '0.7em'
            });

            if (unit == 'c') {
                $('#' + location_id + ' .switchUnitButton').html(units['f']);
            } else {
                $('#' + location_id + ' .switchUnitButton').html(units['c']);
            }

            if(widgetFormat == 'w'){
                $('#'+location_id).addClass('width');
                var format = 'width';
            }else{
                $('#'+location_id).addClass('height');
                var format = 'height';
            }

            $('.myLocationButton').click(function(){
                var locationscript = document.createElement("script");
                locationscript.type = "text/javascript";
                locationscript.src = "https://widget.meteomatics.com/static/js/getlocation.js?format="+ format +"&locateme=" + locateMeOn +"&divId=" + location_id;
                document.getElementsByTagName("head")[0].appendChild(locationscript);
            });

            $('#' + location_id + ' .switchUnitButton').click(function () {
                // change switch button to the other unit
                $('#' + location_id + ' .switchUnitButton').html(units[unit]);
                if (unit == 'c') {
                    unit = 'f'
                } else {
                    unit = 'c'
                }

                for (var i = 0; i < 3; i++) {
                    $('#' + location_id + ' .day .temp1:eq(' + i + ')').html(convertTemperature(initialUnit, unit, tempMaxArray[i]) + units[unit]);
                    $('#' + location_id + ' .day .temp2:eq(' + i + ')').html(convertTemperature(initialUnit, unit, tempMinArray[i]) + units[unit]);
                }
            });

            $('#'+location_id+' .location-widget').html(decodeURIComponent(locationName));
            //fill #today
            for(var i = 0; i < 3; i++){
                $('#'+location_id+' .day .sym:eq('+i+')').addClass('sym_'+ weatherSymbolArray[i]);
                $('#'+location_id+' .day .weekday:eq('+i+')').html(weekday[dateArray[i].getDay()]);
                $('#'+location_id+' .day .temp1:eq(' + i + ')').html(convertTemperature(initialUnit, unit, tempMaxArray[i]) + units[unit]);
                $('#'+location_id+' .day .temp2:eq(' + i + ')').html(convertTemperature(initialUnit, unit, tempMinArray[i]) + units[unit]);
            }
        });
    }
})(); // We call our anonymous function immediately